package cn.mill.core.modem;

import java.lang.reflect.Type;
import java.text.NumberFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.mill.common.Context;
import cn.mill.common.data.Item;
import cn.mill.core.utils.NormUtil;

public class NumberSpell implements FieldSpell {
	
	private static final Logger logger = LoggerFactory.getLogger(NumberSpell.class);
	
	public static final NumberSpell INSTANCE = new NumberSpell();
	
	@Override
	public Item resolver(Context context, String name, Type type, Object object) {
		Item item = new Item();
		item.setName(name);
		item.setType(type);
		if (Double.TYPE == type || Double.class == type) {
			item.setValue(((Double) object).doubleValue());
		}
		if (Long.TYPE == type || Long.class == type) {
			item.setValue(((Long) object).longValue());
		}
		if (Short.TYPE == type || Short.class == type) {
			item.setValue(((Short) object).shortValue());
		}
		if (Float.TYPE == type || Float.class == type) {
			item.setValue(((Float) object).floatValue());
		}
		if (Integer.TYPE == type || Integer.class == type) {
			item.setValue(((Integer) object).intValue());
		}
		return item;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public <T> T builder(Type type, Item item) {
		logger.debug(" type -> " + type.toString() + "   " + item.toString());
		Number number = null;
		if (item != null && item.getValue() != null && String.class == item.getValue().getClass()) {
			String str = item == null ? "" : (String) item.getValue();
			if (NormUtil.isEmpty(str)) {
				str = "0";
			}
			if (str.indexOf("%") >= 0) {
				NumberFormat nf = NumberFormat.getPercentInstance();
				try {
					number = nf.parse(str);
				} catch (Exception e) {
					number = new Double(0);
					logger.error(" format number error->", e);
				}
			} else {
				NumberFormat nf = NumberFormat.getNumberInstance();
				try {
					number = nf.parse(str);
				} catch (Exception e) {
					number = new Double(0);
					logger.error(" format number error->[" + str + "][" + item.toString() + "]", e);
				}
			}
		} else {
			return (T) item.getValue();
		}
		if (Double.TYPE == type || Double.class == type) {
			return (T) Double.valueOf(number.doubleValue());
		}
		if (Long.TYPE == type || Long.class == type) {
			return (T) Long.valueOf(number.longValue());
		}
		if (Short.TYPE == type || Short.class == type) {
			return (T) Short.valueOf(number.shortValue());
		}
		if (Float.TYPE == type || Float.class == type) {
			return (T) Float.valueOf(number.floatValue());
		}
		if (Integer.TYPE == type || Integer.class == type) {
			return (T) Integer.valueOf(number.intValue());
		}
		return null;
	}
	
}
